package com.nhc.activity_fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.astrob.activitys.AppContext;
import com.astrob.model.LonLat;
import com.astrob.model.Msg;
import com.astrob.naviframe.Start;
import com.astrob.nhcmap.R;
import com.astrob.util.SysUtils;
import com.astrob.util.Utils;
import com.astrob.view.BaseViewHolder;
import com.nhc.database.dbmodel.TrackPoint;
import com.nhc.database.dbmodel.WayTrail;
import com.nhc.database.manager.DBDataCenter;
import com.nhc.model.NaviTrackSetInfo;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import zuo.biao.library.base.BaseActivity;
import zuo.biao.library.base.BaseAdapter;
import zuo.biao.library.manager.TimeRefresher;
import zuo.biao.library.model.Entry;
import zuo.biao.library.ui.AlertDialog;
import zuo.biao.library.ui.EditTextInfoActivity;
import zuo.biao.library.ui.EditTextInfoWindow;
import zuo.biao.library.ui.PageScroller;
import zuo.biao.library.ui.TopMenuWindow;
import zuo.biao.library.util.StringUtil;

public class NaviTrackActivity extends BaseActivity implements View.OnClickListener,
        AlertDialog.OnDialogButtonClickListener, TimeRefresher.OnTimeRefreshListener {
    private final String TAG = "NaviTrackActivity";

    //启动方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<


    /**
     * 启动这个Activity的Intent
     *
     * @param context
     * @return
     */
    public static Intent createIntent(Context context) {
        return new Intent(context, NaviTrackActivity.class);
    }
    //启动方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.navitrack_activity);

        //功能归类分区方法，必须调用<<<<<<<<<<
        initView();
        initData();
        initEvent();
        //功能归类分区方法，必须调用>>>>>>>>>>
    }


    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    //示例代码<<<<<<<<
    private ListView lv_navitrack;
    private TextView tvTimedistance;
    private ImageView ivCtrl;
    private Button bt_do;

    //示例代码>>>>>>>>
    @Override
    public void initView() {//必须在onCreate方法内调用
        autoSetTitle();//自动设置标题为上个Activity传入的INTENT_TITLE

        lv_navitrack = (ListView) findViewById(R.id.lv_navitrack);
        tvTimedistance = (TextView) findViewById(R.id.tv_timedistance);
        ivCtrl = (ImageView) findViewById(R.id.iv_ctrl);
        bt_do = (Button) findViewById(R.id.bt_do);
    }

    //示例代码<<<<<<<<
    private DemoAdapter adapter;
    //示例代码>>>>>>>>

    /**
     * 示例方法 ：显示列表内容
     *
     * @param list
     */
    private void setList(List<Entry<Integer, String>> list) {
        if (adapter == null) {
            adapter = new DemoAdapter(context);
            lv_navitrack.setAdapter(adapter);
        }
        adapter.refresh(list);
    }
    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    //示例代码<<<<<<<<
    private List<Entry<Integer, String>> navitracklist;
    private ArrayList<WayTrail> mNaviTrackList = new ArrayList<WayTrail>();

    private boolean mIsEdit = false;//选择删除
    private HashMap<Integer, Boolean> hashMap;

    private boolean getItemChecked(int position) {
        return hashMap.get(position);
    }

    private void setItemChecked(int position, boolean isChecked) {
        if (adapter != null) {
            hashMap.put(position, isChecked);
            adapter.notifyDataSetChanged();
        }
    }

    private void resetWayTrail() {

        ArrayList<WayTrail> naviTrackList = null;

        if (mKey.length() > 0) {
            naviTrackList = DBDataCenter.getInstance().searchWayTrail(mKey);
        } else {
            naviTrackList = DBDataCenter.getInstance().getWaytrailListByOrder(_order);
        }

        //航迹列表，不显示当前的航迹
        //历史航迹的行程距离应该都>0
        mNaviTrackList.clear();
        Long id = DBDataCenter.getInstance().getThisWayTrailID();
        for (WayTrail wt : naviTrackList) {
            if (id == wt.getId()) {
                DBDataCenter.getInstance().reUpdateWayTrail(wt);//当前轨迹的信息只刷一次
                continue;
            }

            mNaviTrackList.add(wt);
            if (!wt.getIsshow()) {
                wt.trackPointList = null;//不显示的航迹，清内存
            }
            //---test-- 正常航迹关闭后,航迹信息已有
            if (wt.getNum() == 0) {
                DBDataCenter.getInstance().reUpdateWayTrail(wt);
                DBDataCenter.getInstance().saveWayTrail(wt, true);
            }
        }
    }

    //示例代码>>>>>>>>>
    @Override
    public void initData() {//必须在onCreate方法内调用
        //示例代码<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
        showProgressDialog(R.string.loading);
        runThread(TAG + "initData", new Runnable() {
            @Override
            public void run() {
                resetWayTrail();
                navitracklist = getList();
                runUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissProgressDialog();
                        setList(navitracklist);
                    }
                });
            }
        });
        //示例代码>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    }

    protected List<Entry<Integer, String>> getList() {
        navitracklist = new ArrayList<Entry<Integer, String>>();
        for (int i = 0; i < mNaviTrackList.size(); i++) {
            navitracklist.add(new Entry<Integer, String>(i, ""));
        }
        return navitracklist;
    }

    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    //Event事件区(只要存在事件监听代码就是)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    @Override
    public void initEvent() {//必须在onCreate方法内调用
        //示例代码<<<<<<<<<<<<<<<<<<<
        findViewById(R.id.currentnavitrack).setOnClickListener(this);
        findViewById(R.id.layout_ctrl).setOnClickListener(this);
        lv_navitrack.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                setResult(RESULT_OK, new Intent().putExtra(RESULT_CLICKED_ITEM, position));
//                finish();
                if (mIsEdit && null != hashMap) {
                    boolean isSelected = hashMap.get(position);
                    hashMap.put(position, !isSelected);
                    if (adapter != null) {
                        adapter.notifyDataSetChanged();
                    }
                    boolean haveselected = false;
                    for (int i = 0; i < mNaviTrackList.size(); i++) {
                        if (hashMap.get(i)) {
                            haveselected = true;
                            break;
                        }
                    }
                    if (haveselected) {
                        bt_do.setText(getString(R.string.delete));
                    } else {
                        bt_do.setText(getString(R.string.cancel));
                    }
                } else {
                    onNaviTrackInfo(position);
                }
            }
        });

        //分页滚动示例代码<<<<<<<<<<<<<<<<<<<
        new PageScroller(lv_navitrack).init();
        //分页滚动示例代码>>>>>>>>>>>>>>>>>>>

        onInitRec();
        refreshInfoForWayTrailThis();

        //示例代码>>>>>>>>>>>>>>>>>>>
    }

    void onNaviTrackInfo(int position) {
        if (position >= 0) {
            DBDataCenter.getInstance().wayTrailEdit = mNaviTrackList.get(position);
        } else  {
            if (DBDataCenter.getInstance().wayTrailThis == null) {
                return;
            }
            DBDataCenter.getInstance().wayTrailEdit = DBDataCenter.getInstance().wayTrailThis;
        }

        showProgressDialog(R.string.loading);
        runThread(TAG + "initData", new Runnable() {
            @Override
            public void run() {
                WayTrail wt = DBDataCenter.getInstance().wayTrailEdit;
                if (wt.trackPointList == null) {
                    wt.trackPointList = DBDataCenter.getInstance().getTrackPointByWayTrail(wt, null);
                    wt.interval = 1;//默认是1秒
                    if (wt.trackPointList.size() > 10) {
                        wt.interval = (int) ((wt.trackPointList.get(9).getDatetime() - wt.trackPointList.get(0).getDatetime()) / 10000);
                    }
                }
                wt.checkGeohash();
                navitracklist = getList();
                runUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissProgressDialog();
                        toActivity(NaviTrackTabActivity.createIntent(getBaseContext()), REQUEST_TO_TRACKDETAIL);
                    }
                });
            }
        });
    }

    //系统自带监听方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    //@user 新增方法
    public void onSave(View v) {
        onCloseRec();
    }

    public void onDelete(View v) {
        //清空当前航迹
        new AlertDialog(context, getString(R.string.wxts), getString(R.string.qdqkdqhj), true, 20, this).show();
    }

    @Override
    protected void onResume() {
        super.onResume();
        TimeRefresher.getInstance().addTimeRefreshListener(TAG, 1000, this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        TimeRefresher.getInstance().removeTimeRefreshListener(TAG);
    }

    @Override
    public void onForwardClick(View v) {
        //top栏右边按钮响应

        toActivity(TopMenuWindow.createIntent(context, getResources().getStringArray(R.array.top_menu_navitrack)), REQUEST_TO_TOP_MENU, false);
    }

    public void onSelectAll(View v) {
        selectAll(true);
    }

    public void onSelectAllNO(View v) {
        selectAll(false);
    }

    public void selectAll(boolean isSelected) {
        if (hashMap == null) {
            hashMap = new HashMap<Integer, Boolean>();
        }
        hashMap.clear();
        if (navitracklist != null) {
            for (int i = 0; i < navitracklist.size(); i++) {
                hashMap.put(i, isSelected);
            }
        }
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        }

        if (isSelected) {
            bt_do.setText(getString(R.string.delete));
        } else {
            bt_do.setText(getString(R.string.cancel));
        }
    }

    public void onDelSelected(View v) {

        boolean haveselected = false;
        for (int i = 0; i < mNaviTrackList.size(); i++) {
            if (hashMap.get(i)) {
                haveselected = true;
                break;
            }
        }

        if (haveselected) {
            new AlertDialog(context, getString(R.string.wxts), getString(R.string.qdscxzdhj), true, 10, this).show();
        } else {
            mIsEdit = false;
            findViewById(R.id.ctrl_navitrack_edit).setVisibility(View.GONE);

            if (adapter != null) {
                adapter.notifyDataSetChanged();
            }
        }

    }

    private void delSelected() {
        mIsEdit = false;
        findViewById(R.id.ctrl_navitrack_edit).setVisibility(View.GONE);
        showShortToast(getString(R.string.deleteok));

        ArrayList<Long> pkIds = new ArrayList<Long>();
        for (int i = 0; i < mNaviTrackList.size(); i++) {
            if (hashMap.get(i)) {
                pkIds.add(mNaviTrackList.get(i).getId());
            }
        }
        DBDataCenter.getInstance().doDeleteWayTrail(pkIds);

        showProgressDialog(R.string.loading);
        runThread(TAG + "initData", new Runnable() {
            @Override
            public void run() {
                resetWayTrail();
                navitracklist = getList();
                runUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissProgressDialog();
                        setList(navitracklist);
                    }
                });
            }
        });
    }

    private void clearListData() {
        DBDataCenter.getInstance().doDeleteAllWayTrail();
        showProgressDialog(R.string.loading);
        runThread(TAG + "initData", new Runnable() {
            @Override
            public void run() {
                resetWayTrail();
                navitracklist = getList();
                runUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissProgressDialog();
                        setList(navitracklist);
                    }
                });
            }
        });
    }

    private void onToEdit() {
        if (navitracklist.size() < 1) {
            showShortToast(getString(R.string.tnotrackdelete));
            return;
        }

        mIsEdit = true;
        findViewById(R.id.ctrl_navitrack_edit).setVisibility(View.VISIBLE);

        selectAll(false);
    }

    @Override
    public void finish() {
        super.finish();
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                break;
        }
        return super.onKeyUp(keyCode, event);
    }

    private final int REQUEST_TO_TOP_MENU = 30;
    private final int REQUEST_TO_EDIT_TEXT_INFO = 32;
    private final int REQUEST_TO_TRACKDETAIL = 33;
    private final int REQUEST_TO_EDIT_TEXT_INFO2 = 34;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (REQUEST_TO_TRACKDETAIL == requestCode) {
            if (resultCode == Msg.DELETE_THIS) {
                ArrayList<Long> pkIds = new ArrayList<Long>();
                pkIds.add(DBDataCenter.getInstance().wayTrailEdit.getId());
                DBDataCenter.getInstance().doDeleteWayTrail(pkIds);
                initData();
                return;
            }
            Long id = DBDataCenter.getInstance().saveWayTrail(DBDataCenter.getInstance().wayTrailEdit, true);
//            if (id == DBDataCenter.getInstance().wayTrailThis.getId()) {
//                //如果编辑的是当前航迹，则恢复保存当前的航迹id
//                SysUtils.getInstance().saveWaytrailID(id);
//            }
            DBDataCenter.getInstance().wayTrailEdit = null;
            if (resultCode == Msg.NAVI_TO_DEST) {
                setResult(resultCode);
                finish();
                return;
            }
            initData();
            return;
        }

        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case REQUEST_TO_EDIT_TEXT_INFO:
                mKey = "";
                if (data != null) {
                    mKey = StringUtil.getTrimedString(
                            data.getStringExtra(EditTextInfoWindow.RESULT_VALUE));
                }
                initData();
                break;
            case REQUEST_TO_EDIT_TEXT_INFO2:
                if (data != null) {
                    String name = StringUtil.getTrimedString(
                            data.getStringExtra(EditTextInfoWindow.RESULT_VALUE));
                    saveThisWayTrail(name);
                }
                break;
            case REQUEST_TO_TOP_MENU:
                if (data != null) {
                    switch (data.getIntExtra(TopMenuWindow.RESULT_POSITION, -1)) {
                        case 0:
                            onToEdit();
                            break;
                        case 1:
                            if (navitracklist.size() > 0) {
                                new AlertDialog(context, getString(R.string.wxts), getString(R.string.qdqkqbhj), true, 11, this).show();
                            } else {
                                showShortToast(getString(R.string.swjl));
                            }
                            break;
                        case 2:
                            onOrder(0);
                            break;
                        case 3:
                            onOrder(1);
                            break;
                        case 4:
                            onOrder(2);
                            break;
                        case 5:
                            onOrder(3);
                            break;
                        case 6:
                            inputKeyword(true);
                            break;
                        case 7:
                            onSetting();
                            break;
                        default:
                            break;
                    }
                }
                break;
        }
    }

    static int _order = 0;

    //"按创建日期排序", "按名称排序", "按距离排序"，"按航点数量排序"
    private void onOrder(int order) {
        mKey = "";
        _order = order;
        initData();
    }

    String mKey = "";

    private void inputKeyword(boolean toWindow) {
        if (toWindow) {
            intent = EditTextInfoWindow.createIntent(context, EditTextInfoWindow.TYPE_NICK
                    , getString(R.string.cxgjz), mKey, getPackageName());
        } else {
            intent = EditTextInfoActivity.createIntent(context, EditTextInfoActivity.TYPE_NICK
                    , getString(R.string.cxgjz), mKey);
        }

        toActivity(intent, REQUEST_TO_EDIT_TEXT_INFO, !toWindow);
    }

    private void onSetting() {
        toActivity(NaviTrackSettingActivity.createIntent(context), 0);
    }

    private void onStartRec() {
        if (mRecState == 1) {
            return;
        }

        if (DBDataCenter.getInstance().wayTrailThis != null) {
            new AlertDialog(context, getString(R.string.wxts), getString(R.string.qdhfjlhj), true, 2, this).show();
            return;
        }
        new AlertDialog(context, getString(R.string.wxts), getString(R.string.qdkqxhj), true, 0, this).show();
    }

    private void onPauseRec() {
        if (DBDataCenter.getInstance().wayTrailThis == null) {
            showShortToast(getString(R.string.dqmyjlhj));
            return;
        }
        new AlertDialog(context, getString(R.string.wxts), getString(R.string.qdztjlhj), true, 1, this).show();
    }

    private void onCloseRec() {
        if (DBDataCenter.getInstance().wayTrailThis == null) {
            showShortToast(getString(R.string.dqmyjlhj));
            return;
        }
        new AlertDialog(context, getString(R.string.wxts), getString(R.string.qdbcdqhj), true, 3, this).show();
    }

    private void onInitRec() {
        if (DBDataCenter.getInstance().wayTrailThis != null) {
            if (DBDataCenter.getInstance().wayTrailThis.getIsPause()) {
                doRec(0);
            } else {
                doRec(1);
            }
        } else {
            doRec(-1);
        }
    }

    int mRecState = -2;//航迹记录状态 -1-关闭  0-暂停 1-记录中

    private void doRec(int state) {
        if (Utils.isFastDoubleClick())
            return;

        if (mRecState == state) {
            return;
        }

        mRecState = state;
        switch (mRecState) {
            default:
                break;
            case 0:
                ivCtrl.setImageResource(R.drawable.btn_rec11);
                break;
            case 1:
                ivCtrl.setImageResource(R.drawable.btn_stop);
                break;
            case -1:
                ivCtrl.setImageResource(R.drawable.btn_rec11);
                tvTimedistance.setText("-----  ---");
                break;
        }
    }

    @Override
    public void onDialogButtonClick(int requestCode, boolean isPositive) {
        if (isPositive == false) {
            return;
        }

        if (requestCode == 10) {
            delSelected();
        } else if (requestCode == 11) {
            clearListData();
        } else if (requestCode == 0) {
            //开启航迹
            DBDataCenter.getInstance().startThisWayTrail();
            doRec(1);
        } else if (requestCode == 1) {
            //暂停航迹
            DBDataCenter.getInstance().pauseThisWayTrail(true);
            doRec(0);
        } else if (requestCode == 2) {
            //暂停结束，恢复记录航迹
            DBDataCenter.getInstance().pauseThisWayTrail(false);
            doRec(1);
        } else if (requestCode == 3) {
            //close save航迹
            ArrayList<TrackPoint> trackPointList = DBDataCenter.getInstance().wayTrailThis.trackPointList;
            if (trackPointList == null || trackPointList.size() < 5) {
                showShortToast(getString(R.string.tsavetrack));
                return;
            }

            editName(true);

        } else if (requestCode == 20) {
            if (DBDataCenter.getInstance().wayTrailThis != null) {
                DBDataCenter.getInstance().wayTrailThis.reset();
                DBDataCenter.getInstance().doDeleteWayTrailTP(DBDataCenter.getInstance().wayTrailThis.getId());
                refreshInfoForWayTrailThis();
                showShortToast(getString(R.string.dqhjyqk));
            }
        }

    }

    private void saveThisWayTrail(String name) {
        DBDataCenter.getInstance().wayTrailThis.setName(name);

        showProgressDialog(R.string.loading);
        runThread(TAG + "initData", new Runnable() {
            @Override
            public void run() {
                boolean isOk = false;
                WayTrail wt = DBDataCenter.getInstance().wayTrailThis;
                wt.trackPointList = DBDataCenter.getInstance().getTrackPointByWayTrail(wt, null);
                if (NaviTrackSetInfo.getInstance().isSaveendclear()) {
                    isOk = DBDataCenter.getInstance().closeThisWayTrail();
                } else {
                    isOk = DBDataCenter.getInstance().saveAsThisWayTrail();
                }
                final boolean saveOk = isOk;

                runUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissProgressDialog();
                        if (saveOk) {
//                            initData();
                            //保存完后，开启新航迹
//                            if (!NaviTrackSetInfo.getInstance().isSaveendclear()) {
//                                DBDataCenter.getInstance().startThisWayTrail();
//                                if (mRecState == 0) {
//                                    DBDataCenter.getInstance().pauseThisWayTrail(true);
//                                    doRec(0);
//                                } else {
//                                    doRec(1);
//                                }
//                            } else {
//                                DBDataCenter.getInstance().wayTrailThis = null;
//                                doRec(-1);
//                            }
                            if (NaviTrackSetInfo.getInstance().isSaveendclear()) {
                                DBDataCenter.getInstance().startThisWayTrail();
                                if (mRecState == 0) {
                                    DBDataCenter.getInstance().pauseThisWayTrail(true);
                                    doRec(0);
                                } else {
                                    doRec(1);
                                }
                            }

                            initData();
                            showShortToast(getString(R.string.hjybc));
                        }
                    }
                });
            }
        });
    }

    private void editName(boolean toWindow) {
        String name = DBDataCenter.getInstance().wayTrailThis.getName();
        if (name.trim().length() < 1) {
            name = SysUtils.getInstance().getTimeStr(System.currentTimeMillis());
        }

        if (toWindow) {
            intent = EditTextInfoWindow.createIntent(context, EditTextInfoWindow.TYPE_NICK
                    , getString(R.string.hjmc), StringUtil.getTrimedString(name), getPackageName());
        } else {
            intent = EditTextInfoActivity.createIntent(context, EditTextInfoActivity.TYPE_NICK
                    , getString(R.string.hjmc), StringUtil.getTrimedString(name));
        }

        toActivity(intent, REQUEST_TO_EDIT_TEXT_INFO2, !toWindow);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.currentnavitrack:
                onNaviTrackInfo(-1);
                break;
            case R.id.layout_ctrl:
//              int mRecState = -2;//航迹记录状态 -1-关闭  0-暂停 1-记录中
                if (mRecState == 1) {
                    onPauseRec();
                } else {
                    onStartRec();
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onTimerStart() {

    }

    @Override
    public void onTimerRefresh() {
        WayTrail wayTrailThis = DBDataCenter.getInstance().wayTrailThis;
        if (wayTrailThis != null && !wayTrailThis.getIsPause()) {
            refreshInfoForWayTrailThis();
        }
    }

    private void refreshInfoForWayTrailThis() {
        WayTrail wayTrailThis = DBDataCenter.getInstance().wayTrailThis;
        if (wayTrailThis != null) {
            wayTrailThis.setEndtime(System.currentTimeMillis());
            int totaltime = (int) (wayTrailThis.getEndtime() - wayTrailThis.getStarttime()) / 1000;
            DecimalFormat DF = new DecimalFormat("00");
            int hour = totaltime / 3600;
            int min = (totaltime % 3600) / 60;
            int second = totaltime % 60;
            String strTime = DF.format(hour) + ":" + DF.format(min) + ":" + DF.format(second);

//            wayTrailThis = DBDataCenter.getInstance().reUpdateWayTrail(wayTrailThis);
            String strDis[] = SysUtils.getInstance().getDistanceStr((int) wayTrailThis.getTrail_distance());
            tvTimedistance.setText(strTime + " " + strDis[0] + strDis[1]);
        }
    }

    @Override
    public void onTimerStop() {

    }


    //系统自带监听方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    //Event事件区(只要存在事件监听代码就是)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Adapter
    public class DemoAdapter extends BaseAdapter<Entry<Integer, String>> {
        public DemoAdapter(Activity context) {
            super(context);
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(
                        R.layout.navitrack_view, parent, false);
            }

            View v_sign = BaseViewHolder.get(convertView, R.id.v_sign);
            TextView tv_navitracklistname = BaseViewHolder.get(convertView, R.id.tv_navitrackname);
            TextView tv_navitracklistdatetime = BaseViewHolder.get(convertView, R.id.tv_navitrackdatetime);
            TextView tv_navitracklistdistance = BaseViewHolder.get(convertView, R.id.tv_navitrackdistance);
            ImageView iv_pic = BaseViewHolder.get(convertView, R.id.iv_pic);
            TextView iv_check = BaseViewHolder.get(convertView, R.id.iv_check);
            iv_check.setTypeface(AppContext.getInstances().getIconfont());

            final Entry<Integer, String> data = getItem(position);
            int index = data.getKey();
            if (index >= 0 && index < mNaviTrackList.size()) {
                WayTrail waytrail = mNaviTrackList.get(index);
                tv_navitracklistname.setText(waytrail.getName());
                tv_navitracklistdatetime.setText(SysUtils.getInstance().getTimeStr(waytrail.getStarttime()));
                String DIS[] = SysUtils.getInstance().getDistanceStr((int) waytrail.getTrail_distance());
                String AREA[] = SysUtils.getInstance().getAreaStr(waytrail.getArea());
                String strDisArea = DIS[0] + DIS[1]
                        + "  " + AREA[0] + AREA[1];
                tv_navitracklistdistance.setText(strDisArea);

                if (waytrail.getIsshow()) {
                    iv_pic.setImageResource(R.drawable.btn_open);
                } else {
                    iv_pic.setImageResource(R.drawable.btn_close);
                }

                iv_check.setVisibility(View.GONE);
                if (mIsEdit) {
                    iv_pic.setVisibility(View.GONE);
                    boolean isSelected = hashMap.get(index);
                    iv_check.setVisibility(View.VISIBLE);
                    if (isSelected) {
                        iv_check.setText(R.string.fonticon_xz);
                    } else {
                        iv_check.setText(R.string.fonticon_wxz);
                    }
                } else {
                    iv_pic.setVisibility(View.VISIBLE);
                }

                v_sign.setBackgroundColor(waytrail.getColor());

                final int clickIndex = index;
                iv_pic.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (clickIndex >= 0 && clickIndex < mNaviTrackList.size()) {
                            WayTrail waytrail = mNaviTrackList.get(clickIndex);
                            boolean isshow = waytrail.getIsshow();
                            waytrail.setIsshow(!isshow);
                            DBDataCenter.getInstance().saveWt(waytrail);
                            adapter.notifyDataSetChanged();
                        }
                    }
                });
            }

            return super.getView(position, convertView, parent);
        }
    }

}
